package com.rabbit.work.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbit.work.constant.OrderSttsConstant;
import com.rabbit.work.mapper.OrderMapper;
import com.rabbit.work.po.Order;
import com.rabbit.work.service.IOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public boolean saveOrder(Order order) {
        Snowflake snowflake = IdUtil.getSnowflake(1);
        order.setId(snowflake.nextId());
        order.setOrderNo(RandomUtil.randomNumbers(10));
        Date date = new Date();
        order.setCreateTime(date);
        order.setUpdateTime(date);
        order.setOrderStts(OrderSttsConstant.ORDER_STTS_CREATE);

        int flag = orderMapper.insert(order);


        rabbitTemplate.send("ew.ttl", "rw.ttl", new Message(order.getOrderNo().getBytes(), MessagePropertiesBuilder.newInstance().build()));

        return flag>0;
    }

    @Override
    @Transactional
    public boolean cancelOrder(Order order) {

        final Order orderDB = orderMapper.selectOne(new QueryWrapper<Order>()
                .eq("order_no", order.getOrderNo())
        );

        if (orderDB == null || orderDB.getOrderStts().intValue() == OrderSttsConstant.ORDER_STTS_CANCEL) {
            System.err.println("无需更新");
            return false;
        }

        final int updated = orderMapper.update(null, new UpdateWrapper<Order>()
                .set("order_stts", OrderSttsConstant.ORDER_STTS_CANCEL)
                .set("update_time", new Date())
                .eq("order_no", order.getOrderNo())
        );

        return updated == 1;
    }

    @Override
    @Transactional
    public boolean payOrder(Order order) {
        final int updated = orderMapper.update(null, new UpdateWrapper<Order>()
                .set("order_stts", OrderSttsConstant.ORDER_STTS_PAYED)
                .eq("order_no", order.getOrderNo())
        );
        return updated == 1;
    }

    @Override
    public List<Order> listOrders(Long userId) {
        return orderMapper.selectList(new QueryWrapper<Order>().eq("user_id", userId));
    }
}
